<template>
	<view class="flex flex-col h-screen">
		<uni-nav-bar title="解答" fixed color="#000" statusBar backgroundColor="transparent" :border="false" left-text="弃答"
			right-text="举报" @clickLeft="handleLeft" @clickRight="handleRight">
		</uni-nav-bar>
		<view class="flex-1 overflow-hidden">
			<scroll-view scroll-y="true" class="h-full">
				<view class="px-20 pb-20" v-if="!loading">
					<view class="relative box-problem mb-20">
						<view class="flex flex-col absolute top-0 left-0 w-full h-full">
							<view class="flex-top"></view>
							<view class="flex-middle flex-1"></view>
							<view class="flex-bottom"></view>
						</view>
						<view class="relative top-0 z-10 p-20 px-30 pb-40">
							<view class="mt-20 problem">
								<text class="font-bold">问题：</text>
								<text>{{postDetail?.describe}}</text>
							</view>
							<view class="mt-20" v-if="postDetail?.replenishment">
								<text class="font-bold">补充说明：</text>
								<text>{{postDetail?.replenishment}}</text>
							</view>
							<template v-if="postDetail.posts == 1">
								<view class="mt-20">
									<text class="text-sm font-bold mb-20">您是否有不适感(可多选):</text>
									<uni-data-checkbox multiple v-model="addparme" :localdata="addparmeList"></uni-data-checkbox>
								</view>
							</template>
							<template v-if="postDetail.posts == 2">
								<view class="mt-20 flex">
									<view class="p-20 bg-[#BBE4FF] text-center rounded-full" @click="onAstrolabe">查看星盘</view>
								</view>
							</template>
							<view v-if="postDetail.posts == 3">
								<view class="mt-20 card-dashed flex justify-around p-20" v-if="cardList.length">
									<view class="flex flex-col justify-center items-center" v-for="(item, idx) in cardList" :key="idx">
										<image :src="item.tarot.front" mode="widthFix" v-if="item.dir == 0"></image>
										<image :src="item.tarot.back" mode="widthFix" v-else></image>
										<!-- <text class="mt-10">{{item.tarot.name}}</text> -->
									</view>
								</view>
								<view class="flex justify-between items-center mt-20 px-50">
									<view class="flex items-center">
										<view class="box-year">2000年</view>
										<view class="box-birthday ml-10">龙</view>
										<view class="box-gender ml-10">女</view>
									</view>
									<view class="flex items-center">
										<view class="choose-num">14</view>
										<view class="choose-num ml-10">29</view>
										<view class="choose-num ml-10">57</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="flex mb-20">
						<view class="box-pay py-10 px-20 ml-10 rounded-full flex items-center">
							<text class="mr-10 text-pay">已支付</text>
							<view class="flex items-center px-20 py-10 rounded-full bg-white">
								<ImageBoxVue :src="postDetail?.paysts==0?'/static/icons/blue.png':'/static/icons/red.png'" width="28rpx"
									height="28rpx">
								</ImageBoxVue>
								<text class="ml-10">{{postDetail?.sinpay}}钻</text>
							</view>
						</view>
					</view>
					<view class="box-rules p-20 mb-20">
						<view class="rules-title flex justify-between items-center px-10" @click="showRules=!showRules">
							<view class="flex items-center">
								<ImageBoxVue src="/static/icons/title.png" width="35rpx" height="29rpx"></ImageBoxVue>
								<text class="text-sm ml-10">重要提示</text>
							</view>
							<ImageBoxVue v-if="showRules" src="/static/icons/arrow_down.png" width="21rpx" height="16rpx">
							</ImageBoxVue>
							<ImageBoxVue v-else src="/static/icons/arrow_up.png" width="21rpx" height="16rpx"></ImageBoxVue>
						</view>
						<view v-show="showRules" class="rules-content">
							请根据以上信息解读问题，并将您的解读方式及依据优先告知用户。<br />
							如:您好，我用数字能量学为您解读问题，根据您所选择的数字14，22，36…<br />
							或:您好，我用卡牌为您解读据系统匹配到的卡牌分别为位倒吊人，逆位圣杯七，正圣杯。骑士……<br />
							或：您好，我用易学为您解读，根据您的生年份及生肖……如不按此格式进行认真解读，平台将收回抢答权限。<br />
							您可以选择语音或文字任意一方式进行解读，只要满足其种解读方式便可提交。
						</view>
					</view>
					<view class="box-rules p-20 mb-20" v-if="anchor.tuto1 == 1">
						<view class="rules-title flex justify-between items-center px-10">
							<view class="flex items-center">
								<ImageBoxVue src="/static/icons/title.png" width="35rpx" height="29rpx"></ImageBoxVue>
								<view class="flex items-center">
									<text class="text-sm ml-10">语音解读</text>
									<text class="text-sm ml-10">|</text>
									<text class="text-sm ml-10 desc">请至少录制30s以上</text>
								</view>
							</view>
						</view>
						<view class="rules-content flex items-start mt-20">
							<view class="flex-1 flex flex-col">
								<template v-if="voiceArr.length">
									<view class="flex items-center justify-center" :class="{'mb-20': idx != voiceArr.length}"
										v-for="(item, idx) in voiceArr" :key="idx">
										<view class="w-60 h-60 rounded-full overflow-hidden">
											<ImageBoxVue :src="anchor.headimg"></ImageBoxVue>
										</view>
										<view class="flex-1 p-10 rounded-full bg-gradient-to-b from-[#94F2FF] to-[#34D3DD] ml-20">
											<view @click="playAudio(item)" class="flex items-center justify-center rounded-full h-44">
												<view class="icon-voice" v-if="item.playing"></view>
												<ImageBoxVue src="/static/user/icon_voice3.png" width="28rpx" height="28rpx" v-else>
												</ImageBoxVue>
												<text class="ml-4 text-white">{{item.time}}''</text>
											</view>
										</view>
										<view class="flex items-center p-10" @click="handleDel(idx)">
											<ImageBoxVue src="/static/icons/delete.png" width="32rpx" height="32rpx"></ImageBoxVue>
											<text class="ml-4">删除</text>
										</view>
									</view>
								</template>
							</view>
							<getSoundVue @createCustomMessage="createCustomMessage"></getSoundVue>
						</view>
					</view>
					<view class="flex justify-center items-center mb-20" @click="handleSubmit" v-if="anchor.tuto1 == 1">
						<view class="btn_rules flex justify-center items-center text-white">确认提交</view>
					</view>
					<view class="box-rules p-20 mb-20" v-if="anchor.tuto1 == 1">
						<view class="rules-title flex justify-between items-center px-10" @click="showText=!showText">
							<view class="flex items-center">
								<ImageBoxVue src="/static/icons/title.png" width="35rpx" height="29rpx"></ImageBoxVue>
								<text class="text-sm ml-10">文字解读</text>
							</view>
							<ImageBoxVue v-if="showText" src="/static/icons/arrow_down.png" width="21rpx" height="16rpx">
							</ImageBoxVue>
							<ImageBoxVue v-else src="/static/icons/arrow_up.png" width="21rpx" height="16rpx"></ImageBoxVue>
						</view>
						<view v-show="!showText" class="rules-content">
							<uni-easyinput type="textarea" autoHeight v-model="params.details" :inputBorder="false"></uni-easyinput>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="flex justify-center items-center pb-60" v-if="anchor.tuto1 == 0" @click="handleRules">
			<view class="flex justify-center items-center text-white" :class="[count==0?'btn_rules':'btn_rules_disabled']">
				我已阅读并遵守<text v-if="count != 0">（{{count}}S）</text>
			</view>
		</view>
		<uni-popup ref="confirmDialogRef" type="dialog">
			<uni-popup-dialog type="warn" cancelText="否" confirmText="是" title="提示" content="确定要放弃解答吗？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app"
	import {
		debounce
	} from '@/config/publicFun.js'
	import communityApi from '@/apis/apiList/communityApi';
	import postCompVue from '@/components/postComp.vue';
	import config from '@/config/index.js'
	import chatFooterVue from './components/chatFooter.vue'
	import userApi from '@/apis/apiList/userApi';
	import getSoundVue from './components/getSound.vue';

	const postId = ref("") // 帖子ID
	const postDetail = ref({}) // 帖子详情
	const loading = ref(false) // 加载中
	const showText = ref(false) // 是否显示文本解读
	const showRules = ref(false) // 是否显示规则
	const btnFlag = ref(false) // 状态切换
	const showKeyWord = ref(false) // 是否显示关键词
	const isAch = ref(0)
	const cardList = ref([])
	const systemSetting = ref([]) // 系统设置列表
	const addparmeList = ref([])
	const textMin = ref(0) // 文字最小长度
	const voiceMin = ref(0) // 语音最小时长
	const textMax = ref(0) // 文字最大长度
	const voiceMax = ref(0) // 语音最大时长
	const chatFootRef = ref(null)
	const confirmDialogRef = ref(null)
	const anchor = ref({}) // 主播信息
	const params = ref({}) // 解读参数
	const recordList = ref([]) // 语音数据
	const voiceArr = ref([]) // 语音列表
	const playing = ref(false)
	const audioCtx = ref(null)
	const count = ref(15) // 倒计时
	const timer = ref(null)

	const addparme = computed(() => { // 不适感
		return postDetail.value.addparme ? postDetail.value.addparme.split(',') : []
	})
	const voiceTime = computed(() => {
		let time = 0
		recordList.value.map(item => {
			let arr = item.split('|')
			time += arr[1]
		})
		return time
	})
	// onMounted(() => {
	// 	addparmeList.value.map(item => {
	// 		item.disable = true
	// 	})
	// })

	onLoad((option) => {
		console.log(option)
		postId.value = option.id;
		loading.value = true
		systemSetting.value = uni.getStorageSync('dict');
		isAch.value = uni.getStorageSync('user').ach
		anchor.value = uni.getStorageSync('anchor')
		addparmeList.value = uni.getStorageSync("addparme")
		params.value['poss.id'] = postId.value
		params.value['anchor.id'] = anchor.value.id
		params.value.sts = 1
	})

	onShow(() => {
		systemSetting.value.map(item => {
			if (item.name == 'QuickPossText_Limit') { // "快速贴文本限制"
				textMin.value = item.minv
				textMax.value = item.maxv
			}
			if (item.name == 'QuickPossMedium_Limit') { // "快速贴媒体时长限制"
				voiceMin.value = item.minv
				voiceMax.value = item.maxv
			}
		})
		getDetail()
		if (anchor.value.tuto1 == 0) {
			showRules.value = true
			countDown()
		}
	})
	// 获取主播信息
	const queryAnchorInfoByMemberId = () => {
		userApi.queryAnchorInfoByMemberId({
			"member.id": uni.getStorageSync('user').id
		}).then(res => {
			anchor.value = res.data
			uni.setStorageSync('anchor', res.data)
		})
	}

	const handleRules = debounce(() => {
		const opt = {
			id: anchor.value.id,
			tuto1: 1
		}
		userApi.upAnchortuto1(opt).then(() => {
			queryAnchorInfoByMemberId()
			showRules.value = false
		})
	})

	const countDown = () => {
		timer.value = setTimeout(() => {
			if (count.value != 0) {
				count.value--
				countDown()
			} else {
				clearTimeout(timer.value)
			}
		}, 1000)
	}

	const handleSubmit = debounce(() => {
		console.log(params.value.details && params.value.details.length < textMin.value)
		if (params.value.details && params.value.details.length < textMin.value) {
			uni.showToast({
				title: `文字内容最短${textMin.value}字`,
				icon: 'none'
			})
			return
		}
		console.log(recordList.value.length && voiceTime.value < voiceMin.value)
		if (recordList.value.length && voiceTime.value < voiceMin.value) {
			uni.showToast({
				title: `语音时长最少${voiceMin.value}秒`,
				icon: 'none'
			})
			return
		}
		uni.showLoading({
			title: '提交中'
		})
		if (recordList.value.length) {
			params.value.headimg = recordList.value.join(',')
		}
		console.log(params.value)
		userApi.anchorpretPossAtquick(params.value).then(res => {
			uni.hideLoading()
			uni.showToast({
				title: '解答成功',
				icon: 'none'
			})
			uni.navigateBack({
				delta: 1
			})
		})
	})
	const handleDel = (idx) => {
		voiceArr.value.splice(idx, 1)
		recordList.value.splice(idx, 1)
	}
	const playAudio = (val) => {
		if (val.playing) {
			audioCtx.value.stop();
			val.playing = false
			audioCtx.value = null
		} else {
			val.playing = true
			audioCtx.value = uni.createInnerAudioContext();
			audioCtx.value.src = val.url; // 在线音频地址
			console.log(audioCtx.value.src);
			audioCtx.value.play();
			audioCtx.value.onEnded((res) => {
				val.playing = false
			})
		}
	}

	const getDetail = () => {
		const opt = {
			id: postId.value,
			'member.id': uni.getStorageSync('user').id
		}
		loading.value = true
		communityApi.getPossInfobyPossid(opt).then(res => {
			postDetail.value = res.data
			loading.value = false
			if (postDetail.value.sdes == 1) {
				getCardList()
			}
		})
	}

	const getCardList = () => {
		const opt = {
			"poss.id": postId.value
		}
		communityApi.getPossTarotlistatPid(opt).then(res => {
			// console.log(res)
			cardList.value = res.data
		})
	}
	// 发送内容
	const sendContent = (content) => {
		const payload = {
			text: content
		}
		params.value.details = content
		console.log('发送消息', payload);
	}
	// 发送自定义信息 data:类型；description：信息；extension：自定义
	const createCustomMessage = (payload) => {
		console.log('发送自定义信息', payload);
		// console.log('发送自定义信息', fromAccount, payload);
		const obj = {
			url: payload.description,
			time: payload.extension,
			playing: false,
		}
		voiceArr.value.push(obj)
		recordList.value.push(`${payload.description}|${payload.extension}`)
	}
	// 弃答
	const handleLeft = () => {
		confirmDialogRef.value.open()
	}
	const dialogClose = () => {
		confirmDialogRef.value.close()
	}
	const dialogConfirm = () => {
		const opt = {
			"anchor.id": uni.getStorageSync('anchor').id,
			"poss.id": postId.value
		}
		userApi.anchorAbandonQuick(opt).then(res => {
			uni.navigateBack({
				delta: 1
			})
		})
	}
	// 举报
	const handleRight = () => {
		uni.navigateTo({
			url: `/pages/user/report?userId=${postDetail.value.member.id}`
		})
	}
	// 跳转星盘
	const onAstrolabe = () => {
		const idsArr = postDetail.value.selcard.split(',')
		uni.navigateTo({
			url: `/pages/test/astrolabe?tab=${idsArr.length>1?0:4}&ids=${postDetail.value.selcard}`
		})
	}
	const handleKeyWord = () => {
		showKeyWord.value = !showKeyWord.value
	}
	const handleGoUser = (router, id, ach) => {
		if (ach == 1) {
			const anchorId = uni.getStorageSync("anchor").id
			if (anchorId != id) {
				onPath(router)
			}
		} else {
			const userId = uni.getStorageSync("user").id
			if (userId != id) {
				onPath(router)
			}
		}
	}
	const onPath = (router) => {
		uni.navigateTo({
			url: router
		})
	}
</script>

<style lang="scss" scoped>
	.box-problem {

		.flex-top {
			background: url('/static/user/bg_top.png') no-repeat;
			background-size: cover;
			height: 258rpx;
		}

		.flex-middle {
			background: url('/static/user/bg_middle.png') repeat-y;
			background-size: contain;
		}

		.flex-bottom {
			background: url('/static/user/bg_bottom.png') no-repeat;
			background-size: cover;
			height: 42rpx;
		}

		.problem {
			background: #FFEFE2;
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			padding: 20rpx;

			text>text {
				font-weight: 500;
				font-size: 24rpx;
				color: #3B4C52;
			}
		}

		.card-dashed {
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			border: 2rpx dashed #8DC2D3;

			image {
				width: 180rpx;
			}
		}
	}

	.box-pay {
		background: #BBE4FF;
		box-shadow: inset 0rpx 0rpx 8rpx 0rpx rgba(32, 121, 202, 0.4);
		border-radius: 120rpx 120rpx 120rpx 120rpx;

		.text-pay {
			font-weight: 400;
			font-size: 32rpx;
			color: #3A5970;
			line-height: 32rpx;
		}

		.pay-num {
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			line-height: 28rpx;
		}
	}

	.box-rules {
		background: linear-gradient(180deg, #F2F8FF 0%, #D0EDFF 100%);
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		border: 2rpx solid;
		border-image: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)) 2 2;

		.rules-title {
			text {
				font-weight: 500;
				font-size: 30rpx;
				color: #333333;

				>text {
					color: #CCCCCC;
				}

				&.desc {
					font-weight: 400;
					font-size: 26rpx;
					color: #47A8FF;
				}
			}
		}

		.rules-content {
			background: #EBF7FF;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			padding: 20rpx;
			font-weight: 400;
			font-size: 24rpx;
			color: #273A3F;
			line-height: 36rpx;
		}
	}

	.box-year {
		background: #E3EDFF;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 2rpx solid #B4CCF7;
		font-weight: 400;
		font-size: 26rpx;
		color: #4370C1;
		line-height: 26rpx;
		padding: 10rpx;
	}

	.box-birthday {
		background: #F2ECFF;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 2rpx solid #E2D4FF;
		font-weight: 400;
		font-size: 26rpx;
		color: #634A97;
		line-height: 26rpx;
		padding: 10rpx;
	}

	.box-gender {
		background: #FFE7D6;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 2rpx solid #FFD8BB;
		font-weight: 400;
		font-size: 26rpx;
		color: #C3743B;
		line-height: 26rpx;
		padding: 10rpx;
	}

	.choose-num {
		background: #E0F0FF;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 2rpx solid #C8E5FF;
		font-size: 32rpx;
		color: #329EFF;
		line-height: 32rpx;
		padding: 10rpx;
	}

	.btn_rules_disabled {
		width: 690rpx;
		height: 80rpx;
		background-image: url('/static/user/bg_read_diaabled.png');
		background-size: cover;
	}

	.btn_rules {
		width: 690rpx;
		height: 80rpx;
		background-image: url('/static/user/bg_read.png');
		background-size: cover;
	}

	.box-card {
		width: 180rpx;
		height: 315.27rpx;
	}

	.line {
		border-bottom: 2rpx dashed #ccc;
	}

	.icon-voice {
		animation-name: voiceExample;
		/* 引用上面定义的@keyframes */
		animation-duration: 3s;
		/* 动画持续时间 */
		animation-iteration-count: infinite;
		/* 无限循环 */
		background: url(/static/user/icon_voice1.png) no-repeat;
		background-size: contain;
		width: 28rpx;
		height: 30rpx;
	}

	@keyframes voiceExample {
		0% {
			background: url(/static/user/icon_voice1.png) no-repeat;
			background-size: contain;
			width: 28rpx;
			height: 30rpx;
		}

		50% {
			background: url(/static/user/icon_voice2.png) no-repeat;
			background-size: contain;
			width: 28rpx;
			height: 30rpx;
		}

		100% {
			background: url(/static/user/icon_voice3.png) no-repeat;
			background-size: cover;
			width: 28rpx;
			height: 30rpx;
		}
	}
</style>